package com.harmony.pilot.agent.service;

import com.harmony.pilot.agent.model.ConversationContext;
import com.harmony.pilot.agent.model.Intent;
import com.harmony.pilot.agent.tools.AgentTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ToolRouter {
    
    @Autowired(required = false)
    private List<AgentTool> tools = new ArrayList<>();
    
    @PostConstruct
    public void init() {
        log.info("ToolRouter initialized with {} tools", tools.size());
        for (AgentTool tool : tools) {
            log.info("Registered tool: {}", tool.getName());
        }
    }
    
    public AgentTool selectTool(Intent intent, ConversationContext context) {
        if (tools == null || tools.isEmpty()) {
            log.warn("No tools available");
            return null;
        }
        
        // 计算每个工具的相关性分数
        List<ToolScore> scores = tools.stream()
            .filter(tool -> tool.canHandle(intent, context))
            .map(tool -> new ToolScore(
                tool,
                tool.getRelevanceScore(intent, context)
            ))
            .sorted(Comparator.comparing(ToolScore::getScore).reversed())
            .collect(Collectors.toList());
        
        if (scores.isEmpty()) {
            log.warn("No tool found for intent: {}", intent.getType());
            return null;
        }
        
        ToolScore best = scores.get(0);
        log.info("Selected tool: {} with score: {}", 
            best.getTool().getName(), best.getScore());
        
        return best.getTool();
    }
    
    public AgentTool getTool(String toolName) {
        if (tools == null) {
            return null;
        }
        return tools.stream()
            .filter(tool -> tool.getName().equals(toolName))
            .findFirst()
            .orElse(null);
    }
    
    public List<AgentTool> getAllTools() {
        return tools != null ? new ArrayList<>(tools) : new ArrayList<>();
    }
    
    private static class ToolScore {
        private final AgentTool tool;
        private final double score;
        
        public ToolScore(AgentTool tool, double score) {
            this.tool = tool;
            this.score = score;
        }
        
        public AgentTool getTool() {
            return tool;
        }
        
        public double getScore() {
            return score;
        }
    }
}

